package com.eds.feign.config;

import feign.Logger;
import feign.RequestInterceptor;
import feign.codec.Decoder;
import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


/**
 * Feign配置类
 * 用于配置Feign客户端的行为
 */
@Configuration
public class FeignConfig {

    /**
     * 创建请求拦截器
     * 用于在Feign请求中添加自定义逻辑，例如添加公共请求头
     *
     * @return 请求拦截器
     */
    @Bean
    public RequestInterceptor requestInterceptor() {
        return requestTemplate -> {
            // 设置请求内容类型
            requestTemplate.header("Content-Type", "application/json");
            requestTemplate.header("Accept", "application/json");
        };
    }

    /**
     * 配置Feign的日志级别
     * 用于调试和监控Feign客户端的请求和响应
     *
     * @return Feign日志级别
     */
    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }

    /**
     * 配置Feign的编码器
     */
    @Bean
    public Encoder feignEncoder() {
        return new SpringFormEncoder(new SpringEncoder(messageConverters()));
    }

    /**
     * 配置Feign的解码器
     */
    @Bean
    public Decoder feignDecoder() {
        return new SpringDecoder(messageConverters());
    }

    private ObjectFactory<HttpMessageConverters> messageConverters() {
        return () -> new HttpMessageConverters();
    }
}